package me.chinaq.fastweb.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import me.chinaq.fastweb.enums.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Shaoqi
 * @date 2015年07月27日
 */
public final class ApiResult<T> implements Serializable {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApiResult.class);

	/**
	 * 响应状态，如果为"OK"则表示验证通过.
	 */
	private int code;
	/**
	 * 提示消息，如果不为空则前台表单验证将提示该消息内容
	 */
	private String msg;
	/**
	 * 返回的主体消息内容
	 */
	private T data;

	public ApiResult() {
	}

	public int getCode() {
		return code;
	}

	public ApiResult<T> setCode(StatusCode code) {
		this.code = code.getCode();
		return this;
	}

	public String getMsg() {
		return msg;
	}

	public ApiResult setMsg(String msg) {
		this.msg = msg;
		return this;
	}

	public T getData() {
		return data;
	}

	public ApiResult setData(T data) {
		this.data = data;
		return this;
	}

	/**
	 * 设置状态为"OK"
	 *
	 * @return
	 * @author Ready
	 * @since 1.0
	 */
	public ApiResult setOK() {
		this.code = StatusCode.SUCCESS.getCode();
		return this;
	}

	/**
	 * 返回默认成功状态的响应对象
	 *
	 * @return
	 */
	public static ApiResult success() {
		return success(null);
	}

	/**
	 * 返回默认成功状态的响应对象，并设置响应内容
	 *
	 * @return
	 */
	public static <T> ApiResult<T> success(T obj) {
		return new ApiResult().setOK().setMsg("操作成功").setData(obj);
	}

	/**
	 * 返回当前对象是否成功状态
	 *
	 * @return
	 */
	public boolean OK() {
		return this.getCode() == StatusCode.SUCCESS.getCode();
	}

	public static <T> ApiResult<T> failed(String msg) {
		return new ApiResult().setCode(StatusCode.FAILED).setMsg(msg);
	}

	public static <T> ApiResult<T> failed(StatusCode status) {
		return new ApiResult().setCode(status).setMsg(status.getLabel());
	}

	@Override
	public String toString() {
		return JSON.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue);
	}

	public static void main(String[] args) {
		String str = "biz.dao.UserMapper";
		String pattern = "\\.\\w+(Mapper)";
		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);

		// 现在创建 matcher 对象
		Matcher m = r.matcher(str);
		if (m.find()) {
			System.out.println(m.group());
			System.out.println("Found value: " + m.group(0));
			System.out.println("Found value: " + m.group(1));
			System.out.println("Found value: " + m.group(2));
			System.out.println("Found value: " + m.group(3));
		} else {
			System.out.println("NO MATCH");
		}
	}

}
